<template>
    <div class="system_setting" style="padding: 0 20px;">
        <!-- 系统设置 -->
        <div class="setting_parmas">
            <header>系统设置</header>
            <main>
                <section>
                    <span class="label">系统别名</span>
                    <el-input v-model="system_title"/>
                    <el-button type="success" @click="changeSystemTitle">保存</el-button>
                    <p class="desc">给系统取一个别名，用户系统的标题</p>
                </section>
                <section v-if="userInfo">
                    <span class="label">系统账号</span>
                    <el-input v-model="userInfo.username" disabled/>
                    <el-button type="success" @click="validateUserCard('user')">设置</el-button>
                    <p class="desc">系统的登录账号</p>
                </section>
                <section v-if="userInfo">
                    <span class="label">系统密码</span>
                    <el-input v-model="userInfo.password" type="password" disabled/>
                    <el-button type="success" @click="validateUserCard('pass')">设置</el-button>
                    <p class="desc">系统的登录密码</p>
                </section>
                <!-- <section>
                    <span class="label">安装路径</span>
                    <el-input v-model="systemInfo.diskInfo.currentPath" type="text" disabled/>
                    <el-button type="success" @click="openFile">查看</el-button>
                    <p class="desc">系统安装在电脑的那个位置</p>
                </section> -->
                <section v-if="userInfo">
                    <span class="label">绑定邮箱</span>
                    <el-input v-model="userInfo.email" type="text" disabled/>
                    <el-button type="success" v-if="!userInfo.email" @click="bindEmailFn">绑定</el-button>
                    <el-button v-else @click="unbindEmailFn">解绑</el-button>
                    <p class="desc">方便用户找回密码</p>
                </section>
            </main>
        </div>
    </div>
 <!-- 系统设置用户名对话框 -->
    <el-dialog
        v-model="system_set_user_dialog"
        title="修改系统用户名"
        draggable
        width="350"
        align-center
        @close="resetUserInfo"
    >
    <el-form ref="updateUserRef" :rules="updateUserRule" :model="updateUsername">
           <!-- 用户名 -->
        <el-form-item prop="username" label="用户名" label-width="70px">
                <el-input
                    style="height: 40px;"
                    v-model="updateUsername.username"
                    class="w-50 m-2"
                    placeholder="用户名"
                >
            </el-input>
        </el-form-item>
        <el-form-item label="重复" label-width="70px">
          <el-input
            style="height: 40px;"
            v-model="updateUsername.repeat_username"
            class="w-50 m-2"
            placeholder="重新输入一遍"
        >
    </el-input>
        </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="system_set_user_dialog = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdateUser">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 系统设置 -->
  <el-dialog
    v-model="system_set_Pass_dialog"
    title="修改系统密码"
    draggable
    width="350"
    align-center
    @close="resetPassInfo"
  >
  <el-form :model="updateUserPass" :rules="updatePassRule" ref="updatePassRef">
    <el-form-item prop="password" lable-width="70px" label="密码">
          <el-input
            style="height: 40px;"
            v-model="updateUserPass.password"
            class="w-50 m-2"
            type="text"
            placeholder="密码"
      >
    </el-input>
        </el-form-item>
        <el-form-item lable-width="70px" label="重复">
          <el-input
            style="height: 40px;"
            v-model="updateUserPass.repeat_password"
            class="w-50 m-2"
            type="password"
            placeholder="重复"
      >
    </el-input>
        </el-form-item>
  </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="system_set_Pass_dialog = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdatePass">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 绑定邮箱 -->
  <el-dialog 
    v-model="emailVisible" 
    title="绑定邮箱"
    width="350"
    draggable
    @close="resetEmail"
   >
    <el-form :rules="bindEmailRule" ref="bindEmailRef" :model="bindEmailModel">
        <el-form-item prop="email" label="邮箱" label-width="70px">
            <el-input v-model="bindEmailModel.email"></el-input>
        </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emailVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBindEmail">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 验证用户的身份 -->
  <el-dialog
    v-model="validUserInfo"
    title="验证用户的身份(输入系统密码)"
    width="350"
    draggable
    @close="handleClose"
  >
    <el-input type="password" v-model="adminUser_pass"></el-input>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="validUserInfo = false">取消</el-button>
        <el-button type="primary" @click="validate_is_admin">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
    import type { FormInstance, FormRules } from 'element-plus'
    import { onMounted,onUnmounted,ref,reactive,getCurrentInstance } from 'vue';
    import * as echarts from 'echarts'
    import {systemInfoPie} from '../../utils/chart'
     import { moduleStore } from '../../store/module'
     import { adminStore } from '../../store/admin';
     let admin_store = adminStore()
     let {system_title} = storeToRefs(admin_store)
    import { storeToRefs } from 'pinia'
     let module_store = moduleStore()
     let {systemInfo} = storeToRefs(module_store)
     import { userStore } from '../../store/user';
     let user_store = userStore()
     let {userInfo} = storeToRefs(user_store)
     let {proxy} = getCurrentInstance()
    // 修改系统的标题
    const changeSystemTitle = () => {
        // 保存到本地
        localStorage.setItem("system_title",system_title.value)
        document.title = system_title.value
        // 用户提醒
        proxy.notifySuccess("修改成功")
    }

    // 系统设置
    let system_set_user_dialog = ref(false)
    let system_set_Pass_dialog = ref(false)
    // 验证用户的身份
    const validateType = ref("")
    const validateUserCard = (type:string) => {
        validateType.value = type // 验证的类型
        validUserInfo.value = true
    }
    // 验证用户是否可以进行修改用户名
const validateUser = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('用户名不能为空'))
  } else if (!(/^[a-zA-Z0-9_-]{4,16}$/.test(value))) {
    callback(new Error("4到16位（字母，数字，下划线，减号"))
  } else {
    callback()
  }
}
const confirmUpdateUser = () => {
    if (!userInfo.value) {
        proxy.$message({type: "error", message: "用户信息未加载，请刷新页面重试"})
        return
    }
    updateUserRef.value?.validate(async (res:any) => {
        if (!res) return proxy.$message({type:"info",message: "请按照要求填写用户名"})
        if (updateUsername.value.repeat_username === '') return proxy.$message({type: "info",message: "用户名不能为空"})
        if (updateUsername.value.repeat_username !== updateUsername.value.username) return proxy.$message({type: "warning",message: "填写的用户名不一致"})
        // 判断是否开启远程监控，修改账号可能会导致使用错误
        if (user_store.deviceList.length !== 0) return proxy.$message({type: "info",message: "请关闭远程监控，否则会导致通信失败"})
        let httpResult = await proxy.$outsideHttp.post("/user/updateUsername",{token: userInfo.value.token,username: updateUsername.value.username})
       if (httpResult.data.code !== 200) return proxy.$message({type: "error",message: "修改用户名失败，请稍后重试"})
       // 提醒用户修改成功
       updateUsername.value.repeat_username = ""
       system_set_user_dialog.value = false
       proxy.$message({type:"success",message: "修改用户名成功"})
       user_store.resetUsername(updateUsername.value.username,httpResult.data.data.newToken) 
    })
}
let updateUsername = ref({
    username: "",
    repeat_username: ""
})
 let updateUserRef = ref<FormInstance>()
  let updateUserRule = reactive<FormRules<any>>({
    username: [{ validator: validateUser, trigger: 'blur' }]
  })

  const resetUserInfo = () => {
    updateUserRef.value?.resetFields()
  }

    /**关于修改密码的代码 */
    const resetPassInfo = () => {
        updatePassRef.value?.resetFields()
    }

  let updateUserPass = ref<any>({
    password: "",
    repeat_password: ""
  })

// 验证密码
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (!(/^[a-zA-Z0-9]{6,12}$/.test(value))) {
    callback(new Error("密码为6-12位，有数字和字母组成"))
  } else {
    callback()
  }
}
// 验证密码规则
let updatePassRule = reactive({
    password: [{ validator: validatePass, trigger: 'blur' }]
  })
  // 修改密码的实列
  let updatePassRef = ref()
  // 确定修改密码
  const confirmUpdatePass = () => {
    if (!userInfo.value) {
        proxy.$message({type: "error", message: "用户信息未加载，请刷新页面重试"})
        return
    }
    updatePassRef.value.validate(async (res:any) => {
        if (!res) return proxy.$message({type:"info",message: "请按照要求填写密码"})
        if (updateUserPass.value.repeat_password === '') return proxy.$message({type:"info",message: "密码不能为空"})
        if (updateUserPass.value.repeat_password !== updateUserPass.value.password) return proxy.$message({type:"warning",message: "密码不一致，请重新输入"})
        
        // 调用修改密码的api接口
       let httpResult = await proxy.$outsideHttp.post("/user/updatePassword",{token: userInfo.value.token,password: updateUserPass.value.password})
       if (httpResult.data.code !== 200) return proxy.$message({type: "error",message: "修改密码错误，请稍后重试"})
       user_store.resetPassword(updateUserPass.value.password)
       // 提醒用户修改成功
       updateUserPass.value.repeat_password = ""
       system_set_Pass_dialog.value = false
       proxy.$message({type:"success",message: "修改密码成功"})
    })
  }

   /**绑定邮箱来找回密码*/
   let emailVisible = ref(false) //控制邮箱对话框显示
   let bindEmailModel = reactive({
        email: ""
   })

   const validateEmail = (rule: any, value: any, callback: any) => {
        if (value == '') {
            callback(new Error("邮箱不能为空"))
        } else if (!(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value))){
            callback(new Error("请输入正确的邮箱"))
        } else {
            callback()
        }
   }
   let bindEmailRef = ref() // 邮箱的实列对象
   let bindEmailRule = reactive({
        email: [{validator: validateEmail,trigger: "blur"}]
   })
   const resetEmail = () => {
     if (bindEmailRef.value) {
       bindEmailRef.value.resetFields()
     }
   }
   // 绑定邮箱
   const bindEmailFn = () => {
     emailVisible.value = true
   }
   // 解绑邮箱
   const unbindEmailFn = async () => {
      if (!userInfo.value) {
          proxy.$message({type: "error", message: "用户信息未加载，请刷新页面重试"})
          return
      }
      let result = await proxy.$outsideHttp.post("/user/unbindEmail",{token: userInfo.value.token})
        if (result.data.code !== 200) return proxy.$message({type:"error",message: "解绑邮箱失败"})
        user_store.resetEmail(bindEmailModel.email)
        proxy.$message({type: "success",message: "解绑成功"})
   }
   const confirmBindEmail = () => {
    if (!userInfo.value) {
        proxy.$message({type: "error", message: "用户信息未加载，请刷新页面重试"})
        return
    }
    bindEmailRef.value.validate(async (res:any) => {
        if (!res) return proxy.$message({type:"warning",message: "请填写正确的邮箱"})
        let result = await proxy.$outsideHttp.post("/user/bindEmail",{token: userInfo.value.token,email: bindEmailModel.email})
        if (result.data.code !== 200) return proxy.$message({type:"error",message: result.data.msg})
        user_store.bindEmail(bindEmailModel.email)
        emailVisible.value = false
        proxy.$message({type:"success",message: "绑定邮箱成功"})
    })
   }
   // 打开系统文件
   const openFile = () => {
    //@ts-ignore
    systemApp.openDialog(systemInfo.value.diskInfo.currentPath)
   }

    /** 验证是否是管理员的用户，否则不能修改系统的用户名或者密码 */
   const validUserInfo = ref(false)
   const adminUser_pass = ref("")
   const handleClose = () => {
     adminUser_pass.value = ""
   }
   // 验证身份
   const validate_is_admin = () => {
     if (!userInfo.value) {
         proxy.$message({type: "error", message: "用户信息未加载，请刷新页面重试"})
         return
     }
     if (userInfo.value.password !== adminUser_pass.value) return proxy.$message({type:"error",message: "身份验证失败"})
     validUserInfo.value = false
     proxy.$message({type:"success",message:"身份验证成功"})
        setTimeout(() => {
        // 审核通过进行下一步
        if (validateType.value == 'user') {
            updateUsername.value.username = userInfo.value.username
            system_set_user_dialog.value = true
        } else if(validateType.value == 'pass') {
            system_set_Pass_dialog.value = true
            updateUserPass.value.password = userInfo.value.password
        }
        },200)
   }
</script>

<style scoped lang="less">
        .system_status {
            padding-top: 10px;
            height: 300px;
            width: 70%;
            header {
                font-size: 20px;
                font-weight: 600;
                height: 60px;
                line-height: 60px;
                display: flex;
                align-items: center;
                &::before {
                    display: inline-block;
                    content: "";
                    width: 8px;
                    height: 32px;
                    background: #63b46b;
                    margin-right: 10px;
                }
            }
            main {
                padding: 10px;
                height: 240px;
                display: flex;
                aside {
                    height: 220px;
                    flex: 1;
                    position: relative;
                    .title {
                        position: absolute;
                        top: -5px;
                        width: 100%;
                        text-align: center;
                        font-size: 18px; 
                        color: #999999;
                    }
                    .desc {
                        position: absolute;
                        width: 100%;
                        height:30px;
                        text-align: center;
                        bottom: -10px;
                        color: #999;
                        font-size: 18px;
                        
                    }
                    .detailInfo {
                        position: absolute;
                        width: 400px;
                        border-radius: 10px;
                        background-color: #FFF;
                        z-index:9;
                        height: 300px;
                        left: 100px;
                        box-shadow: 0 0 6px #5a5a5a;
                        padding: 30px;
                        display: none;
                        .base_info {
                            height: 40px;
                            line-height: 40px;
                            padding-left: 3px;
                            background-color: #f9f9f9;
                        }
                        .aboutMem {
                            list-style: none;
                            display: grid;
                            height: 80px;
                            grid-template-rows: repeat(2,1fr);
                            grid-template-columns: repeat(2,1fr);
                            li {
                                display: flex;
                                justify-content: center;
                                align-items: center;
                            }
                        }
                    }
                    .system_chart {
                        width: 100%;
                        height: 100%;
                    }
                }
            }
}
.setting_parmas {
    header {
        font-size: 20px;
        font-weight: 600;
        height: 60px;
        line-height: 60px;
        display: flex;
        align-items: center;
        &::before {
            display: inline-block;
            content: "";
            width: 8px;
            height: 32px;
            background: #63b46b;
            margin-right: 10px;
        }
    }
    main {
        width: 70%;
        padding-left: 40px;
        padding-top: 10px;
        section {
            display: flex;
            height: 50px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            .label {
                width: 120px;
                font-size: 18px;
                color: #555555;
                line-height: 50px;
                text-align: center;
            }
            .el-input {
                width: 300px;
                margin-right: 10px;
            }
            .el-button {
                margin-right:10px;
            }
            .desc {
                width: 40%;
                color: #999999;
            }
        }
    }
}
</style>